/**
 * File    : LocaleEncoder.java
 * Created : 2008-10-16
 * By      : LuHuiguo
 */
package com.luhuiguo.tapestry.model;

import java.util.Locale;

import org.apache.tapestry5.ValueEncoder;

/**
 * @author LuHuiguo
 * @version $Id: LocaleEncoder.java 2 2008-10-18 04:37:52Z LuHuiguo $
 * 
 */
public class LocaleEncoder implements ValueEncoder<Locale> {

	public LocaleEncoder() {
		super();
	}

	@Override
	public String toClient(Locale value) {
		return value.toString();
	}

	@Override
	public Locale toValue(String clientValue) {
		return toLocale(clientValue);
	}

	public static Locale toLocale(String localeName) {

		String[] terms = localeName.split("_");

		switch (terms.length) {
		case 1:
			return new Locale(terms[0], "");
		case 2:
			return new Locale(terms[0], terms[1]);
		case 3:
			return new Locale(terms[0], terms[1], terms[2]);
		default:
			throw new IllegalArgumentException();
		}
	}

}
